package com.cn.tous.auth.security;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author mengwei
 * @description PasswordAuthenticationConverter
 * @createDate 2025/7/29 15:59
 */
public class PasswordAuthenticationConverter implements AuthenticationConverter {


    private static final Logger log = LoggerFactory.getLogger(PasswordAuthenticationConverter.class);

    @Override
    public Authentication convert(HttpServletRequest request) {
        String grantType = request.getParameter(OAuth2ParameterNames.GRANT_TYPE);
        log.info(" 进入 Grant type: {}", grantType);
        if (!"password".equals(grantType)) {
            return null;
        }

        String username = null;
        String password = null;
        Set<String> requestedScopes = null;

        // 2. 解析用户名和密码
        username = request.getParameter(OAuth2ParameterNames.USERNAME);
        password = request.getParameter(OAuth2ParameterNames.PASSWORD);
        // 3. 解析 scopes (可选)
        String scope = request.getParameter(OAuth2ParameterNames.SCOPE);
        if (StringUtils.hasText(scope)) {
            requestedScopes = new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " ")));
        }

        // 2. 解析用户名和密码
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            throw new OAuth2AuthenticationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST));
        }
//
//        String clientId = request.getParameter(OAuth2ParameterNames.CLIENT_ID);
//        String clientSecret = request.getParameter(OAuth2ParameterNames.CLIENT_SECRET);

        Authentication clientPrincipal = SecurityContextHolder.getContext().getAuthentication();
//        OAuth2ClientAuthenticationToken oAuth2ClientAuthenticationToken  =
//                new OAuth2ClientAuthenticationToken(clientId, ClientAuthenticationMethod.CLIENT_SECRET_BASIC
//                        , clientSecret, new HashMap<>());
//
//        if (clientPrincipal == null ) {
//            clientPrincipal = oAuth2ClientAuthenticationToken;
//        }

        OAuth2PasswordGrantAuthenticationToken passwordGrantAuthenticationToken =
                new OAuth2PasswordGrantAuthenticationToken(
                clientPrincipal,
                requestedScopes,
                username,
                password
        );
        SecurityContextHolder.getContext().setAuthentication(passwordGrantAuthenticationToken);
        return passwordGrantAuthenticationToken;
    }
}
